package cn.edu.gzhu.workOrderManagement.service.impl;

import cn.edu.gzhu.workOrderManagement.constants.WorkOrderFollowStatus;
import cn.edu.gzhu.workOrderManagement.constants.WorkOrderTypeConstant;
import cn.edu.gzhu.workOrderManagement.enumeration.UserAuthorityEnum;
import cn.edu.gzhu.workOrderManagement.enumeration.WorkOrderProcessingStatusEnum;
import cn.edu.gzhu.workOrderManagement.exception.parameterException;
import cn.edu.gzhu.workOrderManagement.mapper.*;
import cn.edu.gzhu.workOrderManagement.pojo.dto.workOrder.*;
import cn.edu.gzhu.workOrderManagement.pojo.dto.workOrderHistory.WorkOrderHistoryListDto;
import cn.edu.gzhu.workOrderManagement.pojo.entity.*;
import cn.edu.gzhu.workOrderManagement.pojo.vo.*;
import cn.edu.gzhu.workOrderManagement.service.WorkOrderService;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static cn.edu.gzhu.workOrderManagement.util.MyBeanUtil.setEmptyStringsToNull;


@Service
public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper,WorkOrder> implements WorkOrderService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SensitiveWordBs sensitiveWordBs;
    @Autowired
    WorkOrderHistoryMapper workOrderHistoryMapper;

    @Autowired
    OrganizationMapper organizationMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WorkOrderMapper workOrderMapper;
    @Autowired
    private TeamMapper teamMapper;

    /**
     * 批量创建工单
     *
     * @param workOrderCreateDtos
     * @return
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createWorkOrder(List<WorkOrderCreateDto> workOrderCreateDtos) {

        Boolean checkRes = checkWorkOrderCreate(workOrderCreateDtos);
        if (!checkRes){
            return false;
        }
        List<WorkOrder> workOrderList = new ArrayList<>();
        for (WorkOrderCreateDto workOrderCreateDto : workOrderCreateDtos) {
            int adder = 0;
            WorkOrder workOrder = new WorkOrder();
            BeanUtils.copyProperties(workOrderCreateDto, workOrder);
            String uuid = generateUniqueUuid(workOrder.getType(), adder);

            while (workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrder>().eq(WorkOrder::getUuid,uuid))!=null) {
                adder += 1;
                uuid = generateUniqueUuid(workOrder.getType(), adder);
            }
            workOrder.setUuid(uuid);
            initWorkOrder(workOrder);
            workOrderList.add(workOrder);
        }
        boolean saveRes = saveBatch(workOrderList);
        if (!saveRes){
            return false;
        }
        return true;
    }

    public IPage<WorkOrderListVo> fuzzySearch(FuzzySearchDto fuzzySearchDto){
        LambdaQueryWrapper<WorkOrder> queryWrapper = new LambdaQueryWrapper<>();
        Page<WorkOrder> page = new Page<>(fuzzySearchDto.getStartPage(), fuzzySearchDto.getPageSize());

        // 条件构造
        queryWrapper.and(wrapper -> wrapper
                .like(WorkOrder::getManualType, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getDelegator, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getRequestUser, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getRequestIdCard, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getLogicalCardNumber, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getCaseNumber, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getHandler, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getCaseBatch, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getTitle, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getPhoneNumber, fuzzySearchDto.getKeyword())
                .or().like(WorkOrder::getTeamName,fuzzySearchDto.getKeyword())
        );

       return getWorkOrderListVoIPage(page,queryWrapper);
    }


    /**
     * 更新工单
     * 此方法只需要修改DTO类就可以增删字段了
     * @param workOrderUpdateDto
     * @return
     */
    @Override

    public Boolean updateWorkOrder(String username,WorkOrderUpdateDto workOrderUpdateDto) {
        //先校验要更新的工单是否存在
        WorkOrder workOrder = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrder>()
                .eq(WorkOrder::getUuid,workOrderUpdateDto.getUuid()).ne(WorkOrder::getIsDeleted,true).eq(WorkOrder::getIsDeleted,false));
        if (workOrder==null){
            throw new  parameterException("工单不存在");

        }
        //再校验工单的branchName、teamId、teamMember,branchLeader是否存在
        if (workOrder.getHandler()==null
                ||workOrder.getBranchName()==null
                ||workOrder.getTeamName()==null
                ||workOrder.getTeamMember()==null
                ||workOrder.getBranchLeader()==null
        ){
            throw new parameterException("Handler，branchName,teamName,teamMember,branchLeader不能为空");
        }
        //查看操作人
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername,username));
        //准备更新
        LambdaUpdateWrapper<WorkOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WorkOrder::getUuid, workOrderUpdateDto.getUuid());
        LocalDateTime updateTime = LocalDateTime.now();
        updateWrapper.set(WorkOrder::getUpdateTime,updateTime);

        //如果是主管转单给处理员，则不需要更新处理状态
        if (!workOrderUpdateDto.getNeedsReassignment()) {

            //处理跟进状态和工单状态

            //根据前端传入的isAdvance判断是进入下一状态还是返回上一级
            WorkOrderProcessingStatusEnum nextStatus = null;
            if (workOrderUpdateDto.getIsAdvance()) {
                nextStatus = workOrder.getProcessingStatus().toNextStatus();
            }
            else {
                nextStatus = workOrder.getProcessingStatus().toPreviousStatus();
            }
            if (nextStatus == null) {
                throw new parameterException("状态错误");
            }

            //更新跟进状态
            String workOrderFollowStatus;
            if (nextStatus.equals(WorkOrderProcessingStatusEnum.getCommonStartStatus())
                    || nextStatus.equals(WorkOrderProcessingStatusEnum.getRepeatStartStatus())
                    || nextStatus.equals(WorkOrderProcessingStatusEnum.getMaterialStartStatus())) {
                workOrderFollowStatus = WorkOrderFollowStatus.WAITING;
            } else if (nextStatus.equals(WorkOrderProcessingStatusEnum.getCommonEndStatus())
                    || nextStatus.equals(WorkOrderProcessingStatusEnum.getRepeatEndStatus())
                    || nextStatus.equals(WorkOrderProcessingStatusEnum.getMaterialEndStatus())) {
                workOrderFollowStatus = WorkOrderFollowStatus.END;
                updateWrapper.set(WorkOrder::getEndTime, LocalDateTime.now());
            } else {
                workOrderFollowStatus = WorkOrderFollowStatus.FOLLOWING;
            }
            updateWrapper.set(WorkOrder::getFollowStatus, workOrderFollowStatus);
            updateWrapper.set(WorkOrder::getProcessingStatus, nextStatus);
        }
        else {
            updateWrapper.set(WorkOrder::getIsReassignment,true);
        }
        //处理上级处理意见
        String reviewComment = workOrderUpdateDto.getReviewComment();
        if (reviewComment==null){
            reviewComment="空";
        }
        LinkedHashMap<String, String> reviewCommentMap = workOrder.getReviewComment();
        reviewCommentMap.put(user.getName()+"&&"+user.getAuthority().getRole()+"&&"+ DateTime.now(),reviewComment);
        updateWrapper.set(WorkOrder::getReviewComment, reviewCommentMap);

        //处理附件

        WorkOrder updatedWorkOrder = new WorkOrder();
        BeanUtils.copyProperties(workOrderUpdateDto, updatedWorkOrder);
        int update = workOrderMapper.update(updatedWorkOrder,updateWrapper);
        //记录历史记录
        workOrderHistoryMapper.insert(WorkOrderHistory.builder().
                uuid(workOrderUpdateDto.getUuid()).
                username(username).updateTime(updateTime).build());
        return update == 1;
    }


    /**
     * 批量删除工单
     * 根据UUID定位，把is_deleted设为true
     * @param uuids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWorkOrder(List<String> uuids) {
        Boolean deleteResult = false;
        int delete = workOrderMapper.delete(new LambdaQueryWrapper<WorkOrder>().in(WorkOrder::getUuid, uuids));
        if (delete >0) {
            deleteResult = true;
        }
        return deleteResult;
    }

    /**
     * 工单分页查询
     *
     * @param workOrderListDto
     * @return
     */
    @Override
    public IPage<WorkOrderListVo> listWorkOrder(WorkOrderListDto workOrderListDto) {
        //添加查询条件
        LambdaQueryWrapper<WorkOrder> queryWrapper = getListQueryWrapper(workOrderListDto);

        // 分页查询
        Page<WorkOrder> page = new Page<>(workOrderListDto.getStartPage(), workOrderListDto.getPageSize());
        return getWorkOrderListVoIPage(page, queryWrapper);
    }

    /**
     * 获取历史工单
     * @param workOrderHistoryListDto
     * @return
     */
    @Override
    public IPage<WorkOrderListVo> listHistoryWorkOrder(String username,WorkOrderHistoryListDto workOrderHistoryListDto) {
        LambdaQueryWrapper<WorkOrderHistory> workOrderHistoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        workOrderHistoryLambdaQueryWrapper.eq(WorkOrderHistory::getUsername,username);
        if (workOrderHistoryListDto.getStartTime()!=null) {
            workOrderHistoryLambdaQueryWrapper.ge(WorkOrderHistory::getUpdateTime,workOrderHistoryListDto.getStartTime());
        }
        if (workOrderHistoryListDto.getEndTime()!=null) {
            workOrderHistoryLambdaQueryWrapper.le(WorkOrderHistory::getUpdateTime,workOrderHistoryListDto.getEndTime());
        }
        List<WorkOrderHistory> workOrderHistories = workOrderHistoryMapper.selectList(workOrderHistoryLambdaQueryWrapper);
        ArrayList<String> uuids = new ArrayList<>();
        workOrderHistories.forEach(workOrderHistory -> {
            uuids.add(workOrderHistory.getUuid());
        });
        if (uuids.isEmpty()){
            return null;
        }
        Page<WorkOrder> page = new Page<>(workOrderHistoryListDto.getStartPage(), workOrderHistoryListDto.getPageSize());
        LambdaQueryWrapper<WorkOrder> workOrderQueryWrapper = new LambdaQueryWrapper<>();
        workOrderQueryWrapper.in(WorkOrder::getUuid,uuids);
        return getWorkOrderListVoIPage(page, workOrderQueryWrapper);
    }

    private IPage<WorkOrderListVo> getWorkOrderListVoIPage(Page<WorkOrder> page, LambdaQueryWrapper<WorkOrder> workOrderQueryWrapper) {
        IPage<WorkOrder> workOrderPage = this.page(page, workOrderQueryWrapper);
        List voList;
        voList = workOrderPage.getRecords().stream()
                .map(workOrder -> {
                    WorkOrderListVo workOrderDetailVo = new WorkOrderListVo();
                    BeanUtils.copyProperties(workOrder, workOrderDetailVo);
                    return workOrderDetailVo;
                }).collect(Collectors.toList());


        IPage<WorkOrderListVo> voPage = new Page<>(workOrderPage.getCurrent(), workOrderPage.getSize(), workOrderPage.getTotal());
        voPage.setRecords(voList);
        return voPage;
    }


    /**
     * 重新流转工单
     * @param workOrderRepeatDto
     * @return
     */
    @Override
    public Boolean repeatWorkOrder(WorkOrderRepeatDto workOrderRepeatDto) {
        String uuid = workOrderRepeatDto.getUuid();
        WorkOrder targetWorkOrder = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrder>().eq(WorkOrder::getUuid, uuid));

        //工单完结前不能重诉
        if (!Objects.equals(targetWorkOrder.getFollowStatus(), WorkOrderFollowStatus.END)) {
            throw new parameterException("工单未完成");
        }
        LambdaUpdateWrapper<WorkOrder> repeatWrapper = new LambdaUpdateWrapper<>();
        //工单状态重设为待处理
        repeatWrapper.set(WorkOrder::getFollowStatus, WorkOrderFollowStatus.WAITING);
       //工单处理流程设置为待总部商务分配
        if (targetWorkOrder.getType().equals(WorkOrderTypeConstant.COMMON)){
           repeatWrapper.set(WorkOrder::getProcessingStatus, WorkOrderProcessingStatusEnum.getCommonStartStatus());
        }
        else if (targetWorkOrder.getType().equals(WorkOrderTypeConstant.REPEAT)){
           repeatWrapper.set(WorkOrder::getProcessingStatus, WorkOrderProcessingStatusEnum.getRepeatStartStatus());
        }
        else if (targetWorkOrder.getType().equals(WorkOrderTypeConstant.MATERIAL)){
           repeatWrapper.set(WorkOrder::getProcessingStatus, WorkOrderProcessingStatusEnum.getMaterialStartStatus());
        }
        //清空原本的处理意见和处理上传的附件和银行处理意见
        /*
        repeatWrapper.set(WorkOrder::getReviewComment,null);
        repeatWrapper.set(WorkOrder::getAnnex,null);
        repeatWrapper.set(WorkOrder::getBankProcessingAdvice,null);
        repeatWrapper.set(WorkOrder::getProcessedDetails,null);
        */

        //设定预警级别
        if (workOrderRepeatDto.getAlertLevel()!=null){
            repeatWrapper.set(WorkOrder::getAlertLevel, workOrderRepeatDto.getAlertLevel());
        }
        //设定预期结束时间
        repeatWrapper.set(WorkOrder::getExpectedEndTime,workOrderRepeatDto.getExpectedEndTime());

        //repeatTime+1
        repeatWrapper.set(WorkOrder::getRepeatTime,targetWorkOrder.getRepeatTime()+1);

        repeatWrapper.set(WorkOrder::getUpdateTime,LocalDateTime.now());

        repeatWrapper.eq(WorkOrder::getUuid,workOrderRepeatDto.getUuid());

        return update(repeatWrapper);
    }

    /**
     * 总部商务修改工单
     *
     * @param workOrderBusUpdateDto
     * @return
     */
    @Override
    public Boolean busUpdate(String username,WorkOrderBusUpdateDto workOrderBusUpdateDto) {
        String uuid = workOrderBusUpdateDto.getUuid();
        WorkOrder targetWorkOrder = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrder>().eq(WorkOrder::getUuid, uuid));
        if (targetWorkOrder==null){
            return false;
        }

        WorkOrder toUpdate =  new WorkOrder();
        BeanUtils.copyProperties(workOrderBusUpdateDto, toUpdate);
        LocalDateTime updateTime = LocalDateTime.now();
        toUpdate.setUpdateTime(updateTime);
        if (toUpdate.getType()!=null){
           toUpdate.setProcessingStatus(determineProcessingStatus(toUpdate.getType(),toUpdate.getBranchName()));
        }

        LambdaQueryWrapper<WorkOrder> workOrderLambdaQueryWrapper = new LambdaQueryWrapper<WorkOrder>().eq(WorkOrder::getUuid, uuid);
        int update = workOrderMapper.update(toUpdate, workOrderLambdaQueryWrapper);
        workOrderHistoryMapper.insert(WorkOrderHistory.builder()
                .uuid(uuid).username(username).updateTime(updateTime).build());
        return update == 1;
    }

    /**
     * 根据uuid获取工单详情
     *
     * @param uuid
     * @return
     */
    @Override
    public WorkOrderDetailVo getWorkOrderDetail(String uuid) {
        WorkOrder workOrder = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrder>().eq(WorkOrder::getUuid, uuid));
        WorkOrderDetailVo workOrderDetailVo = new WorkOrderDetailVo();
        BeanUtils.copyProperties(workOrder, workOrderDetailVo);
        return workOrderDetailVo;
    }

    //添加数据库相关条件的方法

    private static LambdaQueryWrapper<WorkOrder> getListQueryWrapper(WorkOrderListDto workOrderListDto) {
        LambdaQueryWrapper<WorkOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(WorkOrder::getCreateTime);
        // 条件构造
        //时间条件
        if (workOrderListDto.getCreateTimeStart() != null) {
            // 创建时间范围查询：匹配指定日期的全天记录（00:00:00 ~ 23:59:59）
            LocalDate createTimeStart = workOrderListDto.getCreateTimeStart();
            queryWrapper.ge(WorkOrder::getCreateTime, createTimeStart);
        }
        //模糊匹配
        if (workOrderListDto.getClientNumber()!=null){
            queryWrapper.like(WorkOrder::getClientNumber, workOrderListDto.getClientNumber());
        }
        if (workOrderListDto.getCreateTimeEnd() != null) {
            LocalDate createTimeEnd = workOrderListDto.getCreateTimeEnd();
            queryWrapper.le(WorkOrder::getCreateTime, createTimeEnd);
        }
        if (workOrderListDto.getUpdateTimeStart() != null) {
            LocalDate updateTimeStart = workOrderListDto.getUpdateTimeStart();
            queryWrapper.le(WorkOrder::getUpdateTime, updateTimeStart);
        }
        if (workOrderListDto.getUpdateTimeEnd() != null) {
            LocalDate updateTimeEnd = workOrderListDto.getUpdateTimeEnd();
            queryWrapper.le(WorkOrder::getUpdateTime, updateTimeEnd);
        }
        if (workOrderListDto.getEndTimeStart()!=null){
            LocalDate endTimeStart = workOrderListDto.getEndTimeStart();
            queryWrapper.ge(WorkOrder::getEndTime, endTimeStart);
        }
        if (workOrderListDto.getEndTimeStart() != null) {
            LocalDate endTimeStart = workOrderListDto.getEndTimeStart();
            queryWrapper.le(WorkOrder::getEndTime, endTimeStart);
        }
        if (workOrderListDto.getExpectedTimeStart()!=null){
            LocalDate expectedTimeStart = workOrderListDto.getExpectedTimeStart();
            queryWrapper.ge(WorkOrder::getExpectedEndTime, expectedTimeStart);
        }
        if (workOrderListDto.getExpectedTimeEnd()!=null){
            LocalDate expectedTimeEnd = workOrderListDto.getExpectedTimeEnd();
            queryWrapper.le(WorkOrder::getExpectedEndTime, expectedTimeEnd);
        }
        if (workOrderListDto.getTeamName()!=null){
            queryWrapper.like(WorkOrder::getTeamName, workOrderListDto.getTeamName());
        }
        // 请求人姓名精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getRequestUser())) {

            queryWrapper.eq(WorkOrder::getRequestUser, workOrderListDto.getRequestUser());
        }
        // 请求人身份证号模糊匹配
        if (StringUtils.isNotBlank(workOrderListDto.getRequestIdCard())) {

            queryWrapper.eq(WorkOrder::getRequestIdCard, workOrderListDto.getRequestIdCard());
        }
        // 逻辑卡号模糊匹配
        if (StringUtils.isNotBlank(workOrderListDto.getLogicalCardNumber())) {

            queryWrapper.eq(WorkOrder::getLogicalCardNumber, workOrderListDto.getLogicalCardNumber());
        }
        // 关联案件编号精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getCaseNumber())) {

            queryWrapper.eq(WorkOrder::getCaseNumber, workOrderListDto.getCaseNumber());
        }
        // 所属工单精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getType())) {
            queryWrapper.eq(WorkOrder::getType, workOrderListDto.getType());
        }
        // 类型精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getCategory())) {
            queryWrapper.eq(WorkOrder::getCategory, workOrderListDto.getCategory());
        }
        // 工单类型确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getWorkOrderCategory())) {
            queryWrapper.eq(WorkOrder::getWorkOrderCategory, workOrderListDto.getWorkOrderCategory());
        }
        // 跟进状态匹配（如：待处理/处理中/已关闭）
        if (StringUtils.isNotBlank(workOrderListDto.getFollowStatus())) {
            queryWrapper.eq(WorkOrder::getFollowStatus, workOrderListDto.getFollowStatus());
        }
        // 预警级别匹配
        if (workOrderListDto.getAlertLevel() != null) {
            queryWrapper.eq(WorkOrder::getAlertLevel, workOrderListDto.getAlertLevel());
        }
        // 是否监管投诉工单
        if (workOrderListDto.getIsRegulatoryComplaint() != null) {
            queryWrapper.eq(WorkOrder::getIsRegulatoryComplaint, workOrderListDto.getIsRegulatoryComplaint());
        }
        // 经办人查询
        if (StringUtils.isNotBlank(workOrderListDto.getHandler())) {
            queryWrapper.eq(WorkOrder::getHandler, workOrderListDto.getHandler());
        }
        //分支机构负责人精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getBranchLeader())) {
            queryWrapper.eq(WorkOrder::getBranchLeader, workOrderListDto.getBranchLeader());
        }
        //组别精确匹配
        if (workOrderListDto.getTeamId()!=null) {
            queryWrapper.eq(WorkOrder::getTeamId, workOrderListDto.getTeamId());
        }
        // 工单处理状态匹配
        if (workOrderListDto.getProcessingStatus() != null) {
            queryWrapper.eq(WorkOrder::getProcessingStatus, workOrderListDto.getProcessingStatus());
        }
        //归属组员精准匹配
        if (StringUtils.isNotBlank(workOrderListDto.getTeamMember())) {
            queryWrapper.eq(WorkOrder::getTeamMember, workOrderListDto.getTeamMember());
        }

        // 工单标题模糊查询（支持关键词片段搜索）
        if (StringUtils.isNotBlank(workOrderListDto.getTitle())) {
            queryWrapper.like(WorkOrder::getTitle, workOrderListDto.getTitle());
        }
        // 是否敏感工单标记（特殊数据处理标识）
        if (workOrderListDto.getIsSensitive() != null) {
            queryWrapper.eq(WorkOrder::getIsSensitive, workOrderListDto.getIsSensitive());
        }
        // 目标分公司名精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getBranchName())) {

            queryWrapper.eq(WorkOrder::getBranchName, workOrderListDto.getBranchName());
        }
        //手别精准匹配
        if (StringUtils.isNotBlank(workOrderListDto.getManualType())){
            queryWrapper.eq(WorkOrder::getManualType, workOrderListDto.getManualType());
        }
        //工单重复次数精确匹配
        if (workOrderListDto.getRepeatTime()!=null){
            queryWrapper.eq(WorkOrder::getRepeatTime, workOrderListDto.getRepeatTime());
        }
        //委托方精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getDelegator())){
            queryWrapper.eq(WorkOrder::getDelegator, workOrderListDto.getDelegator());
        }
        //委案批次精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getCaseBatch())){
            queryWrapper.eq(WorkOrder::getCaseBatch, workOrderListDto.getCaseBatch());
        }
        //客户手机号精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getPhoneNumber())) {
            queryWrapper.eq(WorkOrder::getPhoneNumber, workOrderListDto.getPhoneNumber());
        }
        //投诉号码精确匹配
        if (StringUtils.isNotBlank(workOrderListDto.getComplaintNumber())){
            queryWrapper.in(WorkOrder::getComplaintNumber, workOrderListDto.getComplaintNumber());
        }
        //是否重诉工单精确匹配
        if (workOrderListDto.getIsKeyComplaint()!=null){
            queryWrapper.eq(WorkOrder::getIsKeyComplaint, workOrderListDto.getIsKeyComplaint());
        }
        if (workOrderListDto.getIsReassignment()!=null){
            queryWrapper.eq(WorkOrder::getIsReassignment, workOrderListDto.getIsReassignment());
        }
        queryWrapper.eq(WorkOrder::getIsDeleted,false);
        return queryWrapper;
    }
    private  Boolean checkWorkOrderCreate(List<WorkOrderCreateDto> workOrderCreateDtoList) {
        if (workOrderCreateDtoList == null || workOrderCreateDtoList.isEmpty()) {
            return false;
        }
        for (WorkOrderCreateDto workOrderCreateDto : workOrderCreateDtoList) {
             /*校验归属分公司、组别、组员
             */

            String branchLeader = workOrderCreateDto.getBranchLeader();
            String branchName = workOrderCreateDto.getBranchName();

            String teamMember = workOrderCreateDto.getTeamMember();
            String handler = workOrderCreateDto.getHandler();
            String teamName = workOrderCreateDto.getTeamName();
            if (branchLeader!=null||branchName!=null||teamMember!=null||handler!=null||teamName!=null) {

                Organization branchOrganization = organizationMapper.selectOne(new LambdaQueryWrapper<Organization>().eq(Organization::getName, branchName));

                User teamUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, teamMember));
                if (teamUser == null  || branchOrganization == null ) {
                    throw new parameterException("填写的分公司或组员不存在");
                }

            }
        }
        return true;
    }
    private void initWorkOrder(WorkOrder workOrder){
        workOrder.setCreateTime(LocalDateTime.now());
        workOrder.setUpdateTime(LocalDateTime.now());
        workOrder.setFollowStatus(WorkOrderFollowStatus.WAITING);
        workOrder.setRepeatTime(0);
        workOrder.setIsReassignment(false);
        for (String content : workOrder.getContent()) {
            if (sensitiveWordBs.contains(content)){
                workOrder.setIsSensitive(true);
            }
        }
        workOrder.setIsDeleted(false);

        workOrder.setProcessingStatus(determineProcessingStatus(workOrder.getType(),workOrder.getBranchName()));
    }
    private String generateUniqueUuid(String type,Integer adder) {
        String prefix = switch (type) {
            case WorkOrderTypeConstant.COMMON -> "C";
            case WorkOrderTypeConstant.REPEAT -> "R";
            case WorkOrderTypeConstant.MATERIAL -> "M";
            default -> "X";
        };
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
        String formatDateTime = localDateTime.format(formatter);

        LocalDate localDate = LocalDate.now();

        LocalDateTime startOfDay = localDate.atStartOfDay();
        LocalDateTime endOfDay = localDate.atTime(23, 59, 59);
        LambdaQueryWrapper<WorkOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkOrder::getType, type);
        wrapper.ge(WorkOrder::getCreateTime, startOfDay);
        wrapper.le(WorkOrder::getCreateTime, endOfDay);

        int count = this.count(wrapper) + 1;
        count = count+adder;
        return prefix + formatDateTime+"_" + count;
    }

    private WorkOrderProcessingStatusEnum determineProcessingStatus(String type,String branchName ) {
        if (type.equals(WorkOrderTypeConstant.COMMON)) {
            if (branchName!=null){
                return WorkOrderProcessingStatusEnum.COMMON_BRANCH_BUS_PENDING;
            }
            else return WorkOrderProcessingStatusEnum.COMMON_HEAD_BUS_PENDING;
        }
        else if (type.equals(WorkOrderTypeConstant.REPEAT)) {
            if (branchName!=null){
                return WorkOrderProcessingStatusEnum.REPEAT_BRANCH_BUS_PENDING;
            }
            else return WorkOrderProcessingStatusEnum.REPEAT_HEAD_BUS_PENDING;
        }
        else {
            if (branchName!=null){
                return WorkOrderProcessingStatusEnum.MATERIAL_BRANCH_BUS_PENDING;
            }
            return WorkOrderProcessingStatusEnum.MATERIAL_HEAD_BUS_PENDING;
        }
    }

    /**
     * @param date
     * @return
     */
    @Override
    public List<WorkOrderStatusAnyVo> getWorkOrderStatusAnalysis(String date) {
        List<WorkOrder> workOrders = getWorkOrderListByDate(date);
        Map<String, Integer> statusCountMap = new HashMap<>();
        String otherStatus = "已超时";
        for (WorkOrder workOrder : workOrders) {
            String status = workOrder.getFollowStatus();
            statusCountMap.put(status, statusCountMap.getOrDefault(status, 0) + 1);
            if (!workOrder.getFollowStatus().equals(WorkOrderFollowStatus.END)
                    && workOrder.getExpectedEndTime() != null
                    && workOrder.getExpectedEndTime().isBefore(LocalDateTime.now())) {
                statusCountMap.put(otherStatus, statusCountMap.getOrDefault(otherStatus, 0) + 1);
            }
        }
        return formatStatusAnyVoList(statusCountMap);
    }

    /**
     * @param date
     * @return
     */
    @Override
    public List<WorkOrderStatusAnyVo> getWorkOrderTypeAnalysis(String date) {
        List<WorkOrder> workOrders = getWorkOrderListByDate(date);
        Map<String, Integer> statusCountMap = new HashMap<>();
        for (WorkOrder workOrder : workOrders) {
            String status = workOrder.getType();
            statusCountMap.put(status, statusCountMap.getOrDefault(status, 0) + 1);
        }
        return formatStatusAnyVoList(statusCountMap);
    }

    private List<WorkOrderStatusAnyVo> formatStatusAnyVoList(Map<String, Integer> statusCountMap) {
        List<WorkOrderStatusAnyVo> workOrderStatusAnyVos = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : statusCountMap.entrySet()) {
            WorkOrderStatusAnyVo workOrderStatusAnyVo = new WorkOrderStatusAnyVo();
            workOrderStatusAnyVo.setStatus(entry.getKey());
            workOrderStatusAnyVo.setCount(entry.getValue());
            workOrderStatusAnyVos.add(workOrderStatusAnyVo);
        }
        return workOrderStatusAnyVos;
    }

    private List<WorkOrder> getWorkOrderListByDate(String date){
        List<WorkOrder> workOrders = new ArrayList<>();
        // 判断传入的日期是日还是月
        if (date == null) {
            // 默认获取当前日期
            date = LocalDate.now().toString();
        }
        LocalDateTime startDateTime;
        LocalDateTime endDateTime;
        if (date.length() == 10) {
            // 日
            LocalDate localDate = LocalDate.parse(date);
            startDateTime = localDate.atStartOfDay();
            endDateTime = localDate.atTime(23, 59, 59);
        } else if (date.length() == 7) {
            // 月
            YearMonth yearMonth = YearMonth.parse(date);
            startDateTime = yearMonth.atDay(1).atStartOfDay();
            endDateTime = yearMonth.atEndOfMonth().atTime(23, 59, 59);
        } else {
            throw new IllegalArgumentException("日期格式错误");
        }
        workOrders = workOrderMapper.selectList(new LambdaQueryWrapper<WorkOrder>()
                .select(WorkOrder::getFollowStatus, WorkOrder::getExpectedEndTime, WorkOrder::getType)
                .between(WorkOrder::getCreateTime, startDateTime, endDateTime));
        return workOrders;
    }

    /**
     * @param month
     * @return
     */
    @Override
    public List<WorkOrderChartAnyVo> getWorkOrderChartAnalysis(Integer month) {
        // 默认查近3个月
        if(month == null){
            month = 3;
        }
        List<WorkOrderChartAnyVo> workOrderChartAnyVos = new ArrayList<>();
        List<WorkOrder> workOrders = workOrderMapper.selectList(new LambdaQueryWrapper<WorkOrder>().ge(WorkOrder::getCreateTime, LocalDate.now().minusMonths(month)));
        Map<String, Integer> statusCountMap = new HashMap<>();
        // 按月份统计yyyy-MM
        for (WorkOrder workOrder : workOrders) {
            String time = workOrder.getCreateTime().toString().substring(0, 7);
            statusCountMap.put(time, statusCountMap.getOrDefault(time, 0) + 1);
        }
        for (Map.Entry<String, Integer> entry : statusCountMap.entrySet()) {
            WorkOrderChartAnyVo workOrderChartAnyVo = new WorkOrderChartAnyVo();
            workOrderChartAnyVo.setTime(entry.getKey());
            workOrderChartAnyVo.setCount(entry.getValue());
            workOrderChartAnyVos.add(workOrderChartAnyVo);
        }
        return workOrderChartAnyVos;
    }

}

